<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use App\Models\Chat;
use App\Models\ChatRoom;
use \Swoole\WebSocket\Server;
class SwooleServer extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole:server';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'swoole websocket';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //创建server
        $server = new \Swoole\WebSocket\Server("0.0.0.0", 9502);
        
        $server->set(array(
            // 'daemonize'=>true  //后台运行
        ));
        //连接成功回调
        $server->on('open', function (\Swoole\WebSocket\Server $server, $request) {
            $this->info($request->fd . '链接成功');
            //查询谁在线
            // $server->push($fd,$content);
        });

        //收到消息回调
        $server->on('message', function (\Swoole\WebSocket\Server $server, $frame) {
            $content = $frame->data;
            $con=json_decode($content,true);
            Log::useFiles(storage_path().'/logs/swoole.log');
            Log::info($con);
            $data['to_id']=$con['to'];
            $data['from_id']=$con['from'];
            $data['room_id']=$con['room_id'];
            $data['content']=$con['msg'];
            $sys = new Chat();
            $sys = $sys->fill($data)->save();
            //推送给所有链接
            foreach ($server->connections as $fd){
                $server->push($fd,$content);
            }
        });

        //关闭链接回调
        $server->on('close', function ($ser, $fd) {
            $this->info($fd . '断开链接');
        });

        $server->start();
    }
}

